package net.llz.service.impl;

import lombok.extern.slf4j.Slf4j;
import net.llz.component.MailService;
import net.llz.constant.CacheKey;
import net.llz.enums.BizCodeEnum;
import net.llz.enums.SendCodeEnum;
import net.llz.service.NotifyService;
import net.llz.util.CheckUtil;
import net.llz.util.CommonUtil;
import net.llz.util.JsonData;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class NotifyServiceImpl implements NotifyService {

    private static final String SUBJECT="子凡验证";
    private static final String CONTENT= "您的验证码是%s,有效时间是10分钟,打死也不要告诉任何人";

    /**
     * 十分钟有效
     */
    private static final int CODE_EXPIRED = 1000 * 60 *10;


    @Autowired
    private MailService mailService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public JsonData sendCode(SendCodeEnum sendCodeType, String to) {

        String cachaKey = String.format(CacheKey.CHECK_CODE_KEY,sendCodeType.name(),to);
        String cachaValue = (String) redisTemplate.opsForValue().get(cachaKey);

        //如果不为空，则判断是否60s内重复发送
        if (StringUtils.isNotBlank(cachaValue)){
            long ttl = Long.parseLong(cachaValue.split("_")[1]);
            if(CommonUtil.getCurrentTimestamp() - ttl <1000 * 60){
                log.info("重复发送验证码，时间间隔：{}秒",((CommonUtil.getCurrentTimestamp()-ttl)/1000));
                return JsonData.buildResult(BizCodeEnum.CODE_LIMITED);
            }
        }

        //验证码 拼接时间戳
        String code = CommonUtil.getRandomCode(6);
        String value = code + "_"+CommonUtil.getCurrentTimestamp();
        redisTemplate.opsForValue().set(cachaKey,value,CODE_EXPIRED, TimeUnit.MILLISECONDS);

        log.info("邮箱验证码{}:",code);
        if (CheckUtil.isEmail(to)){
            //邮箱验证码
            mailService.sendMail(to,SUBJECT,String.format(CONTENT,code));

            return JsonData.buildSuccess();
        }else if (CheckUtil.isPhone(to)){
            //短信验证

        }
        return JsonData.buildResult(BizCodeEnum.CODE_TO_ERROR);
    }


    /**
     * 校验验证码
     * @param sendCodeEnum
     * @param to
     * @param code
     * @return
     */
    @Override
    public Boolean checkCode(SendCodeEnum sendCodeEnum, String to, String code) {
        String captchaKey=String.format(CacheKey.CHECK_CODE_KEY,sendCodeEnum.name(),to);
        String captValue = (String) redisTemplate.opsForValue().get(captchaKey);
        if (StringUtils.isNotBlank(captValue)){
            String cacheCode =captValue.split("_")[0];
            if (cacheCode.equals(code)){

                redisTemplate.delete(captchaKey);
                return true;
            }
        }

        return false;
    }
}
